package com.wecan.components.sms.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.wecan.api.saasdata.UserData;
import com.wecan.base.PO.User;
import com.wecan.base.constants.RedisKey;
import com.wecan.base.model.Result;
import com.wecan.cache.utils.RedisUtil;
import com.wecan.components.sms.DTO.PhoneDTO;
import com.wecan.components.sms.service.SMSService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @Author liuzhihao
 * @Date 2022.02.16
 * @Version ${version}
 * @Description ${description}
 */
@RestController
@RequestMapping(value = "/sms")
public class SMSController {

    @Autowired
    private SMSService smsService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserData userData;

    @Operation(summary = "获取验证码", description = "获取验证码",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = "application/json")),
            responses = {@ApiResponse(description = "获取验证码", content = @Content(mediaType = "application/json"))})
    @Parameters({
            @Parameter(name = "phoneDTO", required = true, description = "获取验证码参数", schema = @Schema(implementation = PhoneDTO.class))
    })
    @PostMapping(value = "/code")
    public Result code(@RequestBody @Valid PhoneDTO phoneDTO) {
        Long userId = StpUtil.getLoginIdAsLong();
        String phone = phoneDTO.getPhone();
        User user = userData.queryUserByPhone(phone);
        if (user != null) {
            if (userId == user.getId()) {
                return Result.failure("手机号已绑定");
            } else {
                return Result.failure("手机号已被他人绑定");
            }
        }
        User user1 = userData.queryUserById(userId);
        if (StringUtils.isNotEmpty(user1.getPhone())) {
            return Result.failure("手机号已绑定");
        }
        String phoneCode = (String) redisUtil.get(RedisKey.PHONE_VALIDATE_CODE + phone);
        if (phoneCode != null) {
            return Result.failure("请勿频繁获取验证码");
        }
        boolean result = smsService.sendSmsCode(phone);
        return result ? Result.success("获取验证码成功") : Result.failure("获取验证码失败");
    }
}
